var successCallback = function (data) {
	time = Date.parse(new Date());
    window.location.href = '/Home/SynPage/community.html?time='+time;
};
var operateRoomTypeErrorCallback = function(error, $obj) {
    if (typeof error.responseJSON == 'undefined') {
        formInlineTip($obj, lang('tip.system'));
    } else if (error.responseJSON.status == 303 && error.status == 403 && error.responseJSON.data != 'error') {
        formInlineTip($obj, lang('type') + error.responseJSON.data + lang('type.exist'));
    } else {
        formInlineTip($obj, error.responseJSON.info);
    }
};
function getQueryString(name) { 
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
	var r = window.location.search.substr(1).match(reg); 
	if (r != null) return unescape(r[2]); return null; 
} 
$(function () {
	$('#navbar-hotel-switch').hide();
	$('#shiyongModel').modal('show');
	$('.showDetailBtn').click(function(){
		var communityName = $(this).attr('data-value');
		var hotel = $(this).attr('data-hotel');
		var params={};
		params.hotel = hotel;
		$('#communityName').text(communityName);
		$.post('/Home/Syn/getSynDetail', params, function(data){
			var accounts = data.data.accounts;
			var rooms = data.data.rooms;
			var i;
			$('#accountList').siblings().remove();
			
			rooms ? $('#synRoom').text(rooms) : $('#synRoom').text(lang('sync.nosync'));
			
			if(accounts[0]){
				for(i in accounts){
					var accountList = $('<div/>').addClass('row vertical-margin');
					var accountName = $('<div/>').addClass('col-xs-3 text-right synItem').text(accounts[i].name);
					var accountMobile = $('<div/>').addClass('col-xs-8 synMobile').text(accounts[i].mobile);
					accountList.append(accountName,accountMobile);
					$('#accountList').after(accountList);
				}
			}else{
				$('#accountList').after('<div class="row vertical-margin"><div class="col-xs-3 text-right synItem">'+lang('sync.nosyncChild')+'</div></div>');
			}
		});
		$('#syn-detail').removeClass('hidden');
	});
	$('#close-btn').click(function(){
		$('#syn-detail').addClass('hidden');
	});
	$('#back-syn-btn').click(function(){
		time = Date.parse(new Date());
		window.location.href = '/Home/SynPage/index.html?hotel='+window.currentHotel+'&time='+time;
	});
	//导入房间下拉
	$('.roomDrapdown').click(function(){
		var id = $(this).attr('id');
		var roomFormat = $('#room'+id);
		if(roomFormat.hasClass('hidden')){
			roomFormat.removeClass('hidden');
			$(this).children().addClass('caret-right');
			$(this).children().removeClass('caret');
		}else{
			roomFormat.addClass('hidden');
			$(this).children().addClass('caret');
			$(this).children().removeClass('caret-right');
		}
		
	});
	//全选
	$(".buildFloor").click(function(){
		var key = $(this).attr("data-value");
		var roomcaret = $("#roomcaret"+key);
		if($(this).is(':checked')){
			roomcaret.find("input").prop("checked",true);
		}else{
			roomcaret.find("input").prop("checked",false);
		}
		
	});
	//某个元素取消选中 则取消全选
	$('.roomName').click(function(){
		if(!$(this).is(':checked')){
			var key = $(this).parents('.roomCheckbox').attr("data-value");
			$("#inlineCheckbox"+key).prop("checked",false);
		}
	});
	//上一步
	$('#backCommunity').click(function(){
		time = Date.parse(new Date());
		window.location.href = '/Home/SynPage/community.html?hotel='+window.currentHotel+'&time='+time;
	});
	$('#successImport').click(function(){
		time = Date.parse(new Date());
		hotel = getQueryString('hotel');
		window.location.href = '/Home/SynPage/index.html?hotel='+hotel+'&time='+time;
	});
	$('#cancelSyn').click(function(){
		time = Date.parse(new Date());
		hotel = getQueryString('hotel');
		window.location.href = '/Home/SynPage/index.html?hotel='+hotel+'&time='+time;
	});
	$('#login-container').inputValidate({
        submit: {
            query: '#requestSubmit'
        },
        inputs: [{
            query: '#requestUsername',
            regexp: window.commonRegexp.mobile,
            message: lang('tip.mobile'),
            emptyMessage: lang('tip.mobileNull')
        }, {
            query: '#requestPassword',
            regexp: window.commonRegexp.password,
            message: lang('tip.password'),
            emptyMessage: lang('tip.passwordNull')
        }]
    });
    $('#requestSubmit').on('successSubmit.amos.inputValidate', function (e) {
        var submitBtn = $(this);
        // 该处可放ajax请求
        submitBtn.attr('disabled', true);
        var params = {};
        params.mobile = $('#requestUsername').val();
        params.password = $('#requestPassword').val();
        params.areaCode = $('.areaCodeValue').text().trim();
		ajaxRequest('/Home/Syn/checkMaster', params, 'post', successCallback, null, submitBtn);
    });

    // 初始化新客栈区号为中国
    var chinaSelectOptionValue = $("#addRequestUniversalTime").find('option[data-areacode=86]').val();
    $("#addRequestUniversalTime").val(chinaSelectOptionValue);

	//添加客栈部分
	//添加客栈自动校验
	$('#addHotelModal').inputValidate({
        submit: {
            query: '#submitAddHotel'
        },
        inputs: [{
            query: '#hotelName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('dealer.name'),
            emptyMessage: lang('dealer.nameNull')
        }]
    });
	// 添加客栈
    $('#submitAddHotel').on('successSubmit.amos.inputValidate', function(e) {
        var param = {
                hotel: $('#hotelName').val().trim(),
                city: $('#cityContainer').find('.tag-selected-container .tag:last-child').data('value'),
                district: $('#districtContainer').find('.tag-selected-container .tag:first-child').data('value'),
                communityNo: $('#communityNo').val().trim(),
				masterentityId :$('#masterentityId').val().trim(),
				universalTime: $('#addRequestUniversalTime').val(),
                currencyId: $('#addRequestMultiCurrency').val()
            },
            $me = $(this);
        if (!param.city || !param.district) {
            formInlineTip($me, lang('dealer.checkAddress'));
            return false;
        }
        formInlineRight($me);
        ajaxRequest('/Home/Syn/addSynHotel', param, 'post', null, null, $me);
    });
	$('.btn-continueSyn').click(function(){
		var hotel = $(this).data('value');
		time = Date.parse(new Date());
		window.location.href = '/Home/SynPage/import.html?'+hotel+'&time='+time;
	})
	$('.btn-createHotel').click(function(){
		var val = JSON.parse($(this).attr('data-json'));
		$('#communityNo').val(val.no);
		$('#masterentityId').val(val.id);
	});
	$('#addHotelModal').on('show.bs.modal', function(e) { 
        window.cityList = citylistArr[4];
	    getCitys(); 
    });  
    $("#addHotelModal #addRequestUniversalTime").change(function(){
        var cityId =parseInt($(this).val())-1 ;
        for(var i = 0;i<citylistArr.length;i++){
            if(cityId == i){
               window.cityList = citylistArr[i]; 
            }
        }
        getCitys();
    });
    //城市初始化
    var getCitys = function(){
        var cityContainer = $('#cityContainer');
        var data = cityContainer.data('amos.tag');
        if (!data) {
            cityContainer.tag({
                removeAtSelected: true,
                selectedTagClickable: false,
                avaliable: window.cityList
            });
            cityContainer.on('selectedClick.amos.tag', selectedClickCity);
            cityContainer.on('beforeSelected.amos.tag', beforeSelectedCity);
        } else {
            cityContainer.tag('resetSelected');
            cityContainer.tag('resetAvaliable');
            cityContainer.tag('addAvaliable', window.cityList);
        }
        var districtContainer = $('#districtContainer');
        data = districtContainer.data('amos.tag');
        if (!data) {
            districtContainer.tag({
                removeAtSelected: false,
                selectedTagClickable: false
            });
            districtContainer.on('selectedClick.amos.tag', selectedClickDistrict);
            districtContainer.on('beforeSelected.amos.tag', beforeSelectedDistrict);
            districtContainer.tag('resetAvaliable');
        } else {
            districtContainer.tag('resetSelected');
            districtContainer.tag('resetAvaliable');
        }
    };    
	var selectedClickCity = function(e, selectedIndex) {
        var cityContainer = $(this);
        var selectedTag = $(e.relatedTarget);
        // 0表示选择省份，1表示选择城市
        if (selectedIndex === 0) {
            cityContainer.tag('resetSelected');
            cityContainer.tag('resetAvaliable');
            cityContainer.tag('addAvaliable', window.cityList);
        } else {
            selectedTag.remove();
            cityContainer.tag('resetAvaliable');
            var value = cityContainer.find('.tag-selected-container .tag').data('value');
            var selectedProvinceCityList = getProvinceCities(value);
            cityContainer.tag('addAvaliable', selectedProvinceCityList);
        }
        var districtContainer = cityContainer.parents('form').find('.districtContainer');
        districtContainer.tag('resetSelected');
        districtContainer.tag('resetAvaliable');
    };
	var beforeSelectedCity = function(e, value) {
        var cityContainer = $(this);
        var selectedSize = cityContainer.find('.tag-selected-container .tag').size();
        // 0表示选择省份，1表示选择城市
        cityContainer.tag('resetAvaliable');
        if (selectedSize === 0) {
            var selectedProvinceCityList = getProvinceCities(value);
            cityContainer.tag('addAvaliable', selectedProvinceCityList);
        } else {
            getCityDistricts(value, cityContainer);
        }
    };
    var selectedClickDistrict = function(e, selectedIndex) {
        var districtContainer = $(this);
        districtContainer.tag('resetSelected');
        districtContainer.find('.tag-avaliable-container').removeClass('hidden');
    };
    var beforeSelectedDistrict = function(e, value) {
        var districtContainer = $(this);
        districtContainer.find('.tag-avaliable-container').addClass('hidden');
    };
	var getCityDistricts = function(value, cityContainer) {
        var params = {};
        params.city = value;
        ajaxRequest('/Home/Position/getDistrict', params, 'post', function(data, cityContainer) {
            var districtContainer = cityContainer.parents('form').find('.districtContainer');
            districtContainer.find('.tag-avaliable-container').removeClass('hidden');
            districtContainer.tag('resetSelected');
            districtContainer.tag('resetAvaliable');
            if (data !== undefined) {
                districtContainer.tag('addAvaliable', data.data);
            }
        }, null, cityContainer);
    };
    var getCityPath = function(cityId) {
        var cityPath = {};
        var selectedProvince = null;
        var selectedCity = {};
        for (var i = 0; i < window.cityList.length; i++) {
            for (var j = 0; j < window.cityList[i].cities.length; j++) {
                if (window.cityList[i].cities[j].id === cityId) {
                    selectedProvince = window.cityList[i];
                    selectedCity = window.cityList[i].cities[j];
                    break;
                }
            }
            if (selectedProvince !== null) {
                break;
            }
        }
        cityPath.province = selectedProvince;
        cityPath.city = selectedCity;
        return cityPath;
    };
    var getProvinceCities = function(value) {
        var selectedProvinceCityList = [];
        for (var i = 0; i < window.cityList.length; i++) {
            if (window.cityList[i].id === value) {
                selectedProvinceCityList = window.cityList[i].cities;
                break;
            }
        }
        return selectedProvinceCityList;
    };
	//客栈部分结束
	
	// 添加房型自动校验
    if (window.hotelUsage == 4) {
        $('#addModal').inputValidate({
            submit: {
                query: '#submitAdd'
            },
            inputs: [{
                query: '#addName',
                regexp: window.commonRegexp.nameLength15,
                message: lang('type.name'),
                emptyMessage: lang('type.nameNull')
            }, {
                query: '#addPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('type.pay'),
                emptyMessage: lang('type.price')
            }, {
                query: '#addCharityPrice',
                regexp: window.commonRegexp.roomTypeCharityPrice,
                message: lang('type.charityPay'),
                emptyMessage: lang('type.charityPrice')
            }]
        });
    } else {
        $('#addModal').inputValidate({
            submit: {
                query: '#submitAdd'
            },
            inputs: [{
                query: '#addName',
                regexp: window.commonRegexp.nameLength15,
                message: lang('type.name'),
                emptyMessage: lang('type.nameNull')
            }, {
                query: '#addPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('type.pay'),
                emptyMessage: lang('type.price')
            }, {
                query: '#addCharityPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('type.pay'),
                emptyMessage: lang('type.charityPrice')
            }]
        });
    }
	
    // 添加房型提交请求
    $('#submitAdd').on('successSubmit.amos.inputValidate', function(e) {
		var $me = $(this),param={};
		var roomInfo = new Array();	
		var roomName = new Array(); 
		var flag = 0;
		param.hotel = getQueryString('hotel');
        param.name = $('#addName').val().trim();
        param.price = $('#addPrice').val().trim();
        if ($('#addCharityPrice').val()) {
            param.charityPrice = $('#addCharityPrice').val().trim();
        }
		$(".roomTypeName").each(function(){
			if($(this).text() == param.name){
				$('#roomTypeRepeat').html(lang('sync.exist')).css({"display":"inline-block","color":"red"});
				flag = 1;
				return;
			}
		});
		var i = 0;
		$(".roomName").each(function(){
			if($(this).is(':checked')){
				roomInfo[i] = $(this).attr('data-value');
				roomName[i] = $(this).attr('room-no');
				if(roomName[i].length>15){
					$('#roomTypeRepeat').html(lang('roomNum')+roomName[i]+lang('sync.maxth15')).css({"display":"inline-block","color":"red"});
					flag = 1;
					return;
				}
				i++;
			}
		});
		if(flag) return false;
		param.roomName = roomName;
		param.roomInfo = roomInfo;
        ajaxRequest('/Home/Syn/addSynRoomType', param, 'post',function(data,$obj){
			if(data.status == 500 || data.status == 501){
				$("#roomTypeRepeat").html(data.data).css({"display":"inline-block","color":"red"});
			}else{
				$obj.attr('disabled', true);
				$('#importRoomTypeBody').modal('hide');
				location.reload();
			}
        }, function(error){
            if (typeof error.responseJSON == 'undefined') {
                $("#roomTypeRepeat").html(lang('tip.system')).css({"display":"inline-block","color":"red"});
            } else {
                $("#roomTypeRepeat").html(error.responseJSON.info).css({"display":"inline-block","color":"red"});
            }
        }, $me);
    });
	$('#allAdminCheckbox').click(function(){
		if ($(this).prop("checked")) {
		$(".addAdminCheckbox").prop('checked',true);
		}else{
			$(".addAdminCheckbox").prop('checked',false);
		}
	})
	$(".addAdminCheckbox").click(function(){
		if (!$(this).prop("checked")) {
			$('#allAdminCheckbox').prop('checked',false);
		}
	})
	$('#submitAdmin').click(function(e) {
        var submitBtn = $(this);
        // submitBtn.attr('disabled', true);
        var params = {};
		var account = new Array();
		var i = 0;
		$(".addAdminCheckbox").each(function(){
			if ($(this).prop("checked")) {
				account[i] = $(this).val();
				i++
			}
		})
		
        params.account = account;
		params.hotel = getQueryString('hotel');
        ajaxRequest('/Home/Syn/addSynSubs', params, 'post', null, null, submitBtn);
    });
	// 删除子账号，显示账号和姓名
    $('#deleteModal').on('show.bs.modal', function(e) {
        var triggerTd = $(e.relatedTarget).parents('td');
        var account = triggerTd.siblings('.mobile').text();
        var name = triggerTd.siblings('.name').text();
        $('#deleteModal .account').html(account);
        $('#deleteModal .name').html(name);
        $('#submitDelete').data('value', triggerTd.attr('account'));
    });
	$('#submitDelete').on('click', function(e) {
        var submitBtn = $(this);
        //   submitBtn.attr('disabled', true);
        var params = {};
        params.account = submitBtn.data('value');
        params.hotel = getQueryString('hotel');
        ajaxRequest('/Home/Syn/deleteSub', params, 'post', function(data){
				submitBtn.attr('disabled', true);
				$('#deleteModal').modal('hide');
				location.reload();
		}, null, submitBtn);
    });
	$('#importRoomType').click(function(){
		$('#importRoomTypeBody').after($('#importRoomBody'));
		$('#roomTypeRepeat').html('').css({"display":"none"});
		$(".styled").prop('checked',false);
	});
	$(".importBtn").click(function(){
		$("#submitAddRoom").data('roomType',$(this).attr('data-value'));
		$("#importRoomHeader").after($('#importRoomBody'));
		$(".styled").prop('checked',false);
		$('#roomRepeat').html('').closest('.form-group').removeClass('has-error');
	});
	
	$("#submitAddRoom").click(function(){
		var submitBtn = $(this);
		var params = {};
		var roomInfo = new Array();
		var roomName = new Array(); 
		var i = 0;
		var flag = 0;
		$(".roomName").each(function(){
			if($(this).is(':checked')){
				roomInfo[i] = $(this).attr('data-value');
				roomName[i] = $(this).attr('room-no');
				if(roomName[i].length>15){
					$('#roomRepeat').html(lang('roomNum')+roomName[i]+lang('sync.maxth15')).css({"display":"inline-block","color":"red"});
					flag = 1;
					return;
				}
				i++
			}
		});
		if(!roomName){
			$("#roomRepeat").html(lang('sync.roomNull')).css({"display":"inline-block","color":"red"});
			flag = 1;
		}
		if(flag) return false;
		params.hotel = getQueryString('hotel');
		params.roomType = submitBtn.data('roomType');
		params.roomName = roomName;
		params.roomInfo = roomInfo;
        ajaxRequest('/Home/Syn/addSynRooms', params, 'post', function(data){
			if(data.status == 500 || data.status == 501){
				$("#roomRepeat").html(data.data).css({"display":"inline-block","color":"red"});
			}else{
				submitBtn.attr('disabled', true);
				$('#importRoomModal').modal('hide');
				location.reload();
			}
		}, function(error){
            if (typeof error.responseJSON == 'undefined') {
                formInlineTip(submitBtn, lang('tip.system'));
            } else {
                formInlineTip(submitBtn, error.responseJSON.info);
            }
        }, submitBtn);
	});
	//删除房间
	$('.roomDeleteEm').click(function(){
		var roomName = $(this).attr('data-room');
		var roomId = $(this).attr('data-value');
		$("#submitRoomDelete").data('roomId', roomId);
		$("#submitRoomDelete").data('roomCount', $(this).parent().siblings().size());
		$('.deleteRoomName').text(roomName);
		$("#roomDeleteTip").html('');
		
	});
	
	$('#submitRoomDelete').on('click', function(e) {
        var submitBtn = $(this);
        var params = {};
        params.roomId = submitBtn.data('roomId');
		params.roomCount = submitBtn.data('roomCount');
        params.hotel = getQueryString('hotel');
		if(params.roomCount){
			ajaxRequest('/Home/Syn/deleteSynRoom', params, 'post', function(data){
				submitBtn.attr('disabled', true);
				$('#deleteRoomModal').modal('hide');
				location.reload();
			}, null, submitBtn);
		}else{
			$("#roomDeleteTip").html(lang('sync.lessOneRoom')).css({"display":"inline-block","color":"red"});
		}
			
    });
    //判断是否显示多元货币
    var defaultId = $('#addRequestMultiCurrency').data('default');
    if(defaultId != ""){
        $('#addRequestMultiCurrency').attr('disabled',true);
        $("#addRequestMultiCurrency").find("option[value='"+defaultId+"']").attr("selected",true);
    }else{
        $('#addRequestMultiCurrency').removeAttr('disabled');
    }
});
